package com.xuan.api.user.controller;


import com.xuan.api.user.service.UserRemoteApiService;
import com.xuan.constant.MQConstant;
import com.xuan.model.entity.User;
import com.xuan.model.respons.ResultBody;
import com.xuan.utils.CommonUtils;
import com.xuan.utils.PhoneUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserRemoteApiService userRemoteApi;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @GetMapping("/register/chekUsername/{username}")
    public ResultBody chekUsername(@PathVariable("username") String username){

        return userRemoteApi.chekUsername(username);
    }

    @PostMapping("/register/savaUser")
    public ResultBody savaUser(@RequestBody User user){

        return userRemoteApi.savaUser(user);
    }

    @GetMapping("/getAll")
    public ResultBody getAll(){
        return userRemoteApi.getAll();
    }

    @GetMapping("/deleteByUsername/{username}")
    public ResultBody deleteByUsername(@PathVariable("username") String username){
        return userRemoteApi.deleteByUsername(username);
    }

    @GetMapping("/sendSms/{mobile}")
    public ResultBody sendSms(@PathVariable("mobile") String mobile){
        if (PhoneUtils.isChinaPhoneLegal(mobile)){//判断手机号是否合格
            //查询手机号是否存在
            if (userRemoteApi.chekMobile(mobile)){
                try {
                    //生成验证码
                    String code = CommonUtils.generateCode();
                    Map<String,Object> map =  new HashMap<>();
                    map.put("code",code);
                    map.put("mobile",mobile);
                    rabbitTemplate.convertAndSend(MQConstant.SEND_SMS_DIRECT_EXCHANGE,MQConstant.SEND_SMS_KEY_BINDING,map);
                    log.info("手机号为===="+mobile+";;;验证码为====="+code);
                    return new ResultBody<String>().OK("发送成功").data(code);
                } catch (AmqpException e) {
                    e.printStackTrace();
                    return new ResultBody().Fail("信息发送失败");
                }
            }
            return new ResultBody().Fail("手机号已存在,请更改密码或更换手机号进行验证");
        }
        return new ResultBody().Fail("手机号不正确");
    }


    @PostMapping("/reset/password")
    public ResultBody resetPassword(@RequestBody User user){
        return userRemoteApi.resetPassword(user);
    }
}
